//----------------------------------------------
//            NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------

using UnityEngine;
using System.Collections.Generic;
using WXB;

[ExecuteInEditMode]
[RequireComponent(typeof(UISprite))]
public class UISpriteAnim : MonoBehaviour
{
    AnimData mAnimData;
    bool mActive;
    UISprite mSprite;
    public bool isPlaying { get { return mActive; } }

    static void SetUISprite(UISprite sprite, Image image)
    {
        sprite.atlas = image.atlas;
        sprite.spriteName = image.name;
    }

    int mIndex = 0;
    float mDelta = 0;
    bool loop = true;
    void Update()
    {
        if (mActive && mAnimData != null && mAnimData.images.Count > 1 && Application.isPlaying && mAnimData.speed > 0f)
        {
            mDelta += RealTime.deltaTime;
            float rate = mAnimData.speed;

            if (rate < mDelta)
            {
                mDelta = (rate > 0f) ? mDelta - rate : 0f;
                if (++mIndex >= mAnimData.images.Count)
                {
                    mIndex = 0;
                    mActive = loop;
                }

                if (mActive)
                {
                    SetUISprite(mSprite, mAnimData.images[mIndex]);
                    mSprite.MakePixelPerfect();
                }
            }
        }
    }
}
